package com.example.hw01.servlet;

import com.example.hw01.model.Product;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "ProductServlet", value = "/products")
public class ProductServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        // 初始化商品数据
        List<Product> products = new ArrayList<Product>();
        products.add(new Product(1, "苹果", 5.0, 100, "新鲜红富士苹果"));
        products.add(new Product(2, "牛奶", 8.0, 50, "纯牛奶250ml"));
        products.add(new Product(3, "面包", 10.0, 30, "全麦面包"));
        products.add(new Product(4, "鸡蛋", 1.5, 200, "新鲜鸡蛋"));

        // 设置为应用上下文属性，所有用户共享
        getServletContext().setAttribute("products", products);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 检查用户是否登录
        HttpSession session = request.getSession();
        if (session.getAttribute("user") == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        // 转发到商品列表页面
        request.getRequestDispatcher("productList.jsp").forward(request, response);
    }
}